package com.xiaoshu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshu.user.entity.TUser;
import com.xiaoshu.user.mapper.TUserMapper;
import com.xiaoshu.user.service.ITUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类, 添加额外功能： 添加缓存的使用（基于Redis，集成SpringCache）
 * 目的： 通过缓存数据，提高查询效率；
 * </p>
 *
 * @author deane
 * @since 2021-06-16
 */
@Service
@Slf4j
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    @Override
    @Cacheable(value = {"users"}, key = "'user:userId:' + #p0")
    public TUser getUserByUserId(String userId) {
        log.info("[find User by UserId] userId is : {}", userId);
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.getOne(queryWrapper);
    }

    @Override
    @Caching(
        evict = {
            @CacheEvict(value = {"users"}, key = "'user:userId:' + #p0")
        }
    )
    public void updateUserByUserId(String userId, TUser user) {
        UpdateWrapper<TUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("user_name", user.getUserName());
        updateWrapper.set("password", user.getPassword());
        updateWrapper.set("nick_name", user.getNickName());
        updateWrapper.set("id_card", user.getIdCard());
        updateWrapper.eq("user_id", userId);
        this.update(updateWrapper);
    }

    @Override
    @CacheEvict(value = {"users"}, key = "'user:userId:' + #p0")
    public void deleteUserByUserId(String userId) {
        this.baseMapper.deleteUserByUserId(userId);
    }

    @Override
    @CachePut(value = {"users"}, key = "'user:userId:' + #p0.userId")
    public TUser saveUser(TUser user) {
        this.save(user);
        return user;
    }

}
